package com.ruoyi.info.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.util.security.AppScanUtil;
import com.ruoyi.util.security.Result;
import com.ruoyi.util.security.WxqbResult;
import com.ruoyi.util.security.WxqbUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.info.domain.CmsApp;
import com.ruoyi.info.service.ICmsAppService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * appController
 * 
 * @author xwj
 * @date 2023-08-01
 */
@Controller
@RequestMapping("/cms/app")
public class CmsAppController extends BaseController
{
    private String prefix = "cms/app";

    @Autowired
    private ICmsAppService cmsAppService;
    @Autowired
    private ISysConfigService configService;


    @GetMapping()
    public String app()
    {
        return prefix + "/app";
    }

    /**
     * 查询app列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CmsApp cmsApp)
    {
        startPage();
        List<CmsApp> list = cmsAppService.selectCmsAppList(cmsApp);
        return getDataTable(list);
    }

    /**
     * 导出app列表
     */
    @Log(title = "app", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CmsApp cmsApp)
    {
        List<CmsApp> list = cmsAppService.selectCmsAppList(cmsApp);
        ExcelUtil<CmsApp> util = new ExcelUtil<CmsApp>(CmsApp.class);
        return util.exportExcel(list, "app数据");
    }

    /**
     * 新增app
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存app
     */
    @Log(title = "app", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CmsApp cmsApp)
    {
        return toAjax(cmsAppService.insertCmsApp(cmsApp));
    }

    /**
     * 修改app
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        CmsApp cmsApp = cmsAppService.selectCmsAppById(id);
        mmap.put("cmsApp", cmsApp);
        return prefix + "/edit";
    }

    /**
     * 修改保存app
     */
    @Log(title = "app", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CmsApp cmsApp)
    {
        return toAjax(cmsAppService.updateCmsApp(cmsApp));
    }

    /**
     * 删除app
     */
    @Log(title = "app", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(cmsAppService.deleteCmsAppByIds(ids));
    }


    @PostMapping( "/uploadApp")
    @ResponseBody
    public AjaxResult uploadApp(MultipartFile file, String lx) throws Exception {
        SysUser currUser = getSysUser();
        Result result = cmsAppService.uploadApp(currUser, file, lx);

        if(result.isError()) {
            return AjaxResult.error(result.getError());
        }
        return AjaxResult.success();
    }

    @PostMapping("/listPage")
    @ResponseBody
    public TableDataInfo listPage(CmsApp cmsApp)
    {
        startPage();
        SysUser currUser = getSysUser();
        cmsApp.setUserId(currUser.getUserId());
        List<CmsApp> list = cmsAppService.selectCmsAppList(cmsApp);
        return getDataTable(list);
    }

    @GetMapping("/refresh/{id}")
    @ResponseBody
    public AjaxResult refresh(@PathVariable Long id) {
        CmsApp app = cmsAppService.selectCmsAppById(id);

        Result result = cmsAppService.refreshRemote(app);

        if(result.isError()) {
            return AjaxResult.error(result.getError());
        }

        return AjaxResult.success();
    }

    @PostMapping("/refreshAll")
    @ResponseBody
    public AjaxResult refreshAll() {
        List<CmsApp> apps = cmsAppService.findNotSuccess();
        for(CmsApp app : apps) {
            cmsAppService.refreshRemote(app);
        }
        return AjaxResult.success();
    }

    @GetMapping("/pdf")
    public void pdf(@RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        Long id = Convert.toLong(params.get("id")) ;

        CmsApp app = cmsAppService.selectCmsAppById(id);
        File file = AppScanUtil.getPdfUrl(app);

        String fileName = file.getName();
        System.out.println(file.getPath());

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, fileName);
        FileUtils.writeBytes(file.getPath(), response.getOutputStream());
        FileUtils.deleteFile(file.getPath());
    }

    /**
     * 威胁情报
     */
    @GetMapping("/wxqbQuery")
    @ResponseBody
    public AjaxResult wxqbQuery(@RequestParam Map<String, Object> params) throws Exception {
        System.out.println("----------------value:" + params);

        String apikey = configService.selectConfigByKey("wxqb.apikey");
        String host = configService.selectConfigByKey("wxqb.host");
        String salt = configService.selectConfigByKey("wxqb.salt");

        WxqbResult result = WxqbUtil.query(host, apikey, salt, params);

        if(result == null) {
            return AjaxResult.error();
        }

        if(!"2000".equals(result.getErrno())) {
            return AjaxResult.error(result.getMsg());
        }

        String resultStr = result.getResult();

        JSONObject jo =  JSON.parseObject(resultStr);



        return AjaxResult.success();
    }


}
